/**
 * 前端API配置
 * 提供统一的API调用接口
 */

// API配置对象
const ApiConfig = {
    // 基础配置
    baseUrl: 'http://localhost:5000',
    timeout: 3000000,
    retryCount: 3,

    // 文档API配置
    documentApi: {
        baseUrl: 'http://localhost:5000/api/document',
        endpoints: {
            list: '/list',
            upload: '/upload',
            detail: '/{id}',
            delete: '/{id}',
            update: '/{id}',
            process: '/{id}/process',
            reprocess: '/{id}/reprocess',
            stats: '/stats'
        }
    },

    // 问答API配置
    qaApi: {
        baseUrl: 'http://localhost:5000/api/qa',
        endpoints: {
            sessions: '/sessions',
            sessionDetail: '/sessions/{id}',
            sessionMessages: '/sessions/{id}/messages',
            chat: '/chat',
            ask: '/ask',
            feedback: '/feedback',
            export: '/sessions/{id}/export',
            stats: '/stats'
        }
    },

    /**
     * 构建完整的API URL
     * @param {string} baseUrl - 基础URL
     * @param {string} endpoint - 端点
     * @param {Object} parameters - 查询参数
     * @returns {string} 完整的URL
     */
    buildUrl: function(baseUrl, endpoint, parameters = null) {
        let url = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) + endpoint : baseUrl + endpoint;
        
        if (parameters && Object.keys(parameters).length > 0) {
            const queryString = Object.keys(parameters)
                .map(key => `${key}=${encodeURIComponent(parameters[key])}`)
                .join('&');
            url += `?${queryString}`;
        }
        
        return url;
    },

    /**
     * 替换URL中的占位符
     * @param {string} url - URL
     * @param {Object} placeholders - 占位符值
     * @returns {string} 替换后的URL
     */
    replacePlaceholders: function(url, placeholders) {
        let result = url;
        for (const [key, value] of Object.entries(placeholders)) {
            result = result.replace(`{${key}}`, value);
        }
        return result;
    },

    /**
     * 获取文档API URL
     * @param {string} endpoint - 端点名称
     * @param {Object} placeholders - 占位符
     * @param {Object} parameters - 查询参数
     * @returns {string} 完整的URL
     */
    getDocumentApiUrl: function(endpoint, placeholders = null, parameters = null) {
        const endpointPath = this.documentApi.endpoints[endpoint];
        if (!endpointPath) {
            throw new Error(`未知的文档API端点: ${endpoint}`);
        }

        let url = this.buildUrl(this.documentApi.baseUrl, endpointPath, parameters);
        
        if (placeholders) {
            url = this.replacePlaceholders(url, placeholders);
        }
        
        return url;
    },

    /**
     * 获取问答API URL
     * @param {string} endpoint - 端点名称
     * @param {Object} placeholders - 占位符
     * @param {Object} parameters - 查询参数
     * @returns {string} 完整的URL
     */
    getQaApiUrl: function(endpoint, placeholders = null, parameters = null) {
        const endpointPath = this.qaApi.endpoints[endpoint];
        if (!endpointPath) {
            throw new Error(`未知的问答API端点: ${endpoint}`);
        }

        let url = this.buildUrl(this.qaApi.baseUrl, endpointPath, parameters);
        
        if (placeholders) {
            url = this.replacePlaceholders(url, placeholders);
        }
        
        return url;
    },

    /**
     * 发送GET请求
     * @param {string} url - 请求URL
     * @returns {Promise} 响应数据
     */
    get: function(url) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: url,
                method: 'GET',
                timeout: this.timeout,
                success: function(response) {
                    resolve(response);
                },
                error: function(xhr, status, error) {
                    console.error('GET请求失败:', {url, status, error});
                    reject({
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText,
                        error: error
                    });
                }
            });
        });
    },

    /**
     * 发送POST请求
     * @param {string} url - 请求URL
     * @param {Object} data - 请求数据
     * @returns {Promise} 响应数据
     */
    post: function(url, data) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: url,
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                timeout: this.timeout,
                success: function(response) {
                    resolve(response);
                },
                error: function(xhr, status, error) {
                    console.error('POST请求失败:', {url, data, status, error});
                    reject({
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText,
                        error: error
                    });
                }
            });
        });
    },

    /**
     * 发送PUT请求
     * @param {string} url - 请求URL
     * @param {Object} data - 请求数据
     * @returns {Promise} 响应数据
     */
    put: function(url, data) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: url,
                method: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(data),
                timeout: this.timeout,
                success: function(response) {
                    resolve(response);
                },
                error: function(xhr, status, error) {
                    console.error('PUT请求失败:', {url, data, status, error});
                    reject({
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText,
                        error: error
                    });
                }
            });
        });
    },

    /**
     * 发送DELETE请求
     * @param {string} url - 请求URL
     * @returns {Promise} 响应数据
     */
    delete: function(url) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: url,
                method: 'DELETE',
                timeout: this.timeout,
                success: function(response) {
                    resolve(response);
                },
                error: function(xhr, status, error) {
                    console.error('DELETE请求失败:', {url, status, error});
                    reject({
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText,
                        error: error
                    });
                }
            });
        });
    },

    /**
     * 上传文件
     * @param {string} url - 请求URL
     * @param {FormData} formData - 表单数据
     * @returns {Promise} 响应数据
     */
    upload: function(url, formData) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: url,
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                timeout: this.timeout,
                success: function(response) {
                    resolve(response);
                },
                error: function(xhr, status, error) {
                    console.error('文件上传失败:', {url, status, error});
                    reject({
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText,
                        error: error
                    });
                }
            });
        });
    },

    /**
     * 带重试的请求
     * @param {Function} requestFn - 请求函数
     * @param {number} maxRetries - 最大重试次数
     * @returns {Promise} 响应数据
     */
    retry: function(requestFn, maxRetries = this.retryCount) {
        return new Promise((resolve, reject) => {
            let retryCount = 0;
            
            const attempt = () => {
                requestFn()
                    .then(resolve)
                    .catch(error => {
                        retryCount++;
                        if (retryCount <= maxRetries) {
                            console.log(`请求失败，第${retryCount}次重试...`);
                            setTimeout(attempt, 1000 * retryCount); // 递增延迟
                        } else {
                            reject(error);
                        }
                    });
            };
            
            attempt();
        });
    }
};

// 导出到全局作用域
window.ApiConfig = ApiConfig;

// 初始化日志
console.log('API配置已加载:', {
    baseUrl: ApiConfig.baseUrl,
    documentApi: ApiConfig.documentApi.baseUrl,
    qaApi: ApiConfig.qaApi.baseUrl
}); 